﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//using DNA.Mvc.Models;
using System.Web.UI;
using DNA.Mvc.jQuery;

namespace DNA.Mvc.UI
{
    public class WidgetView : ViewComponent
    {
        public WidgetInstance Model { get; set; }
        public WidgetView() 
        {
            UserPreferencesTemplate = new HtmlTemplate<WidgetHelper>();
            ContentTemplate = new HtmlTemplate<WidgetHelper>();
            DesignTemplate = new HtmlTemplate<WidgetHelper>();
            PreviewTemplate = new HtmlTemplate<WidgetHelper>();
        }
        public HtmlTemplate<WidgetHelper> UserPreferencesTemplate { get; set; }

        public HtmlTemplate<WidgetHelper> ContentTemplate { get; set; }

        public HtmlTemplate<WidgetHelper> DesignTemplate { get; set; }

        public HtmlTemplate<WidgetHelper> PreviewTemplate { get; set; }

        public bool IsDesignMode
        {
            get
            {
                var result = false;
                var request = ViewContext.HttpContext.Request;
                if (request.IsAjaxRequest())
                {
                    if (request.QueryString["design"] != null)
                        bool.TryParse(request.QueryString["design"], out result);
                }
                else
                {
                    if (ViewContext.RouteData.Values.ContainsKey("design"))
                        bool.TryParse(ViewContext.RouteData.Values["design"] as string, out result);
                }
                return result;
            }
        }

        public override void Render(HtmlTextWriter writer)
        {
            var html = new HtmlHelper(ViewContext, ViewDataContainer);
            //var ajax = new AjaxHelper(ViewContext, ViewDataContainer);

            bool isPreviewMode = false;
            Dictionary<string, PropertyDescriptor> propertyDescriptors = null;
            Dictionary<string, object> userdata = new Dictionary<string, object>();

            var bag = ViewContext.Controller.ViewBag;
            if (bag != null)
            {
                if (bag.PropertyDescriptors != null)
                {
                    propertyDescriptors = bag.PropertyDescriptors as Dictionary<string, PropertyDescriptor>;
                    if (propertyDescriptors != null)
                    {
                        foreach (var key in propertyDescriptors.Keys)
                            userdata.Add(key, propertyDescriptors[key].Value);
                    }
                }

                if (bag.IsPreview != null)
                    isPreviewMode = bag.IsPreview;

                //if (bag.WidgetInstance!=null)
                Model = bag.WidgetInstance;
            }

            //if (this.ViewContext.TempData.Count > 0)
            //{
            //    if (this.ViewContext.TempData.ContainsKey("PropertyDescriptors"))
            //    {
            //        propertyDescriptors = (Dictionary<string, PropertyDescriptor>)ViewContext.TempData["PropertyDescriptors"];
            //        foreach (var key in propertyDescriptors.Keys)
            //            userdata.Add(key, propertyDescriptors[key].Value);
            //    }

            //    if (ViewContext.TempData.ContainsKey("IsPreview"))
            //       Boolean.TryParse(ViewContext.TempData["IsPreview"].ToString(), out isPreviewMode);
                

            //    if (ViewContext.TempData.ContainsKey("WidgetInstance"))
            //        Model = this.ViewContext.TempData["WidgetInstance"] != null ? (WidgetInstance)this.ViewContext.TempData["WidgetInstance"] : null;
            //}

            var widgetHelper = new WidgetHelper()
            {
                Model = Model,
                UserPreferences = userdata,
                PropertyDescriptors = propertyDescriptors
            };

            if (isPreviewMode)
            {
                if (!PreviewTemplate.IsEmpty)
                    PreviewTemplate.WriteTo(widgetHelper,writer);
                else
                {
                    if (!ContentTemplate.IsEmpty)
                        ContentTemplate.WriteTo(widgetHelper,writer);
                }
            }
            else
            {
                if (IsDesignMode)
                {
                    if (userdata.Count > 0)
                    {
                        //writer.Write(ajax.RenderAutoSettingForm(propertyDescriptors, widgetHelper.IDPrefix, true).ToString());
                        writer.WriteBeginTag("form");
                        writer.WriteAttribute("class", "d-widget-userpreferences");
                        writer.WriteAttribute("action", "#");
                        writer.Write(HtmlTextWriter.TagRightChar);

                        if (!UserPreferencesTemplate.IsEmpty)
                        {
                            UserPreferencesTemplate.WriteTo(widgetHelper,writer);
                        }
                        else
                        {
                            foreach (var key in propertyDescriptors.Keys)
                            {
                                if (propertyDescriptors[key].PropertyControl != ControlTypes.Checkbox)
                                {
                                    writer.WriteBeginTag("div");
                                    writer.WriteAttribute("style", "clear:both");
                                    writer.Write(HtmlTextWriter.TagRightChar);
                                    writer.Write(propertyDescriptors[key].DisplayName);
                                    writer.WriteEndTag("div");
                                }
                                writer.WriteFullBeginTag("div");
                                RenderPropertyControl(writer, widgetHelper, propertyDescriptors[key]);
                                writer.WriteEndTag("div");
                            }
                        }
                        writer.WriteEndTag("form");
                    }
                    if (!DesignTemplate.IsEmpty)
                        DesignTemplate.WriteTo(widgetHelper,writer);
                    else
                        if (!ContentTemplate.IsEmpty)
                            ContentTemplate.WriteTo(widgetHelper, writer);
                }
                else
                {
                    if (!ContentTemplate.IsEmpty)
                        ContentTemplate.WriteTo(widgetHelper, writer);
                }
            }



            writer.Write(html.StartupScripts().ToString());
        }

        private void RenderPropertyControl(HtmlTextWriter writer, WidgetHelper helper, PropertyDescriptor descriptor)
        {
            var ajax = new AjaxHelper(ViewContext, ViewDataContainer);
            string fieldID = helper.GenerateFieldID(descriptor.Name);
            switch (descriptor.PropertyControl)
            {
                case ControlTypes.TextArea:
                    writer.Write(ajax.Dna().TextArea(fieldID)
                        .Value(descriptor.Value == null ? "" : descriptor.Value.ToString())
                        .GetHtml());
                    break;
                case ControlTypes.Checkbox:
                    writer.Write(ajax.Dna().Checkbox(fieldID, descriptor.DisplayName, (bool)descriptor.Value).GetHtml());
                    break;
                case ControlTypes.DateTimePicker:
                    writer.Write(ajax.Dna().DatePicker(fieldID)
                        .Value(DateTime.Parse(descriptor.Value.ToString()))
                        .GetHtml());
                    break;
                case ControlTypes.Number:
                    writer.Write(ajax.Dna().TextBox(fieldID)
                        .NumericOnly()
                        .Value(descriptor.Value.ToString())
                        .GetHtml());
                    break;
                case ControlTypes.Slider:
                    writer.Write(ajax.Dna().Slider(fieldID)
                        .Value((int)descriptor.Value)
                        .GetHtml());
                    break;
                case ControlTypes.Radiobox:
                    break;
                case ControlTypes.Richtext:
                    writer.Write(ajax.Dna().RichTextBox(fieldID)
                        .Value(descriptor.Value.ToString())
                        .Resizable()
                        .GetHtml());
                    break;
                default:
                    writer.Write(ajax.Dna().TextBox(fieldID)
                        .Value(descriptor.Value == null ? "" : descriptor.Value.ToString())
                        .GetHtml());
                    break;
            }
        }
    }
}